<template>
  <div class="box">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
     <el-card>
      <div class="box1">
        <el-button type="primary" @click="add">添加角色</el-button>
        <el-table :data="tableData" border height="500">
          <el-table-column fixed prop="date" type="expand">
            <template slot-scope="scope">
              <el-row v-for="item in scope.row.children" :key="item.id">
                <!-- 一级权限 -->
                <el-col :span="5">
                  <i class="el-icon-caret-right"></i>
                  <!-- 给el-tag添加绑定close事件处理函数removeRightById(scope.row,item.id) 删除权限-->
                  <el-tag
                    closable
                    @close="removeRightById(scope.row, item.id)"
                    >{{ item.authName }}</el-tag
                  >
                  <!-- 二级权限三级权限 -->
                </el-col>
                <el-col :span="19">
                  <!-- for循环嵌套二级权限 -->
                  <el-row v-for="item1 in item.children" :key="item1.id">
                    <!-- 二级权限 -->
                    <el-col :span="6">
                      <el-tag
                        type="success"
                        @close="removeRightById(scope.row, item1.id)"
                        >{{ item1.authName }}</el-tag
                      >
                      <!-- 三级权限 -->
                    </el-col>
                    <el-col :span="18">
                      <el-tag
                        v-for="item2 in item1.children"
                        :key="item2.id"
                        @close="removeRightById(scope.row, item2.id)"
                        >{{ item2.authName }}</el-tag
                      >
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column type="index" label="#"> </el-table-column>
          <el-table-column prop="roleName" label="角色名称"> </el-table-column>
          <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="edit(scope.row.id)"
                >编辑</el-button
              >
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="del(scope.row.id)"
                >删除</el-button
              >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setting(scope.row)"
                >分配权限</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 添加角色 -->
      <el-dialog title="添加用户" :visible.sync="dialogFormVisible">
        <el-form :model="form" ref="ruleForm" :rules="rules">
          <el-form-item
            label="角色名称"
            prop="roleName"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model="form.roleName"
              placeholder="请输入角色名称"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="角色描述"
            prop="roleDesc"
            :label-width="formLabelWidth"
          >
            <el-input v-model="form.roleDesc" placeholder="请输入角色描述">
            </el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="adds">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 编辑提交角色 -->
      <el-dialog title="添加用户" :visible.sync="dialog">
        <el-form :model="forms" ref="editruleForm" :rules="rules">
          <el-form-item
            label="角色名称"
            prop="roleName"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model="forms.roleName"
              placeholder="请输入角色名称"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="角色描述"
            prop="roleDesc"
            :label-width="formLabelWidth"
          >
            <el-input v-model="forms.roleDesc" placeholder="请输入角色描述">
            </el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialog = false">取 消</el-button>
          <el-button type="primary" @click="editform">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 分配权限 -->
      <el-dialog
        title="分配权限"
        :visible.sync="dialogdata"
        @close="setRightDialogClose"
      >
        <el-tree
          :data="rightsdata"
          show-checkbox
          node-key="id"
          default-expand-all:
          :default-checked-keys="defKeys"
          ref="treeRef"
          :props="defaultProps"
        >
        </el-tree>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogdata = false">取 消</el-button>
          <el-button type="primary" @click="settingform">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: "",
  data() {
    return {
      tableData: [], //角色数据
      formLabelWidth: "120px",
      dialogFormVisible: false, //添加确定
      dialog: false, //编辑确定
      dialogdata: false, //分配确定
      //添加数据参数
      form: {
        roleName: "",
        roleDesc: "",
      },
      forms: {}, //编辑数据参数
      rightsdata: [], //分配权限列表数据
      //添加用户正则
      rules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
      },
      defKeys: [], //默认选中的节点id值数组
      defaultProps: {
        children: "children",
        label: "authName",
      },
      roleId: "", //当前要分配的权限角色的id
    };
  },
  created() {},
  mounted() {
    this.getroles();
  },
  methods: {
    handleClick(row) {},
    //获取角色数据
    getroles() {
      this.$axios.get("roles").then((res) => {
        if (res.data.meta.status != 200) {
          this.$message.error("获取角色失败");
        } else {
          this.$message.success("获取角色成功");
        }
        this.tableData = res.data.data;
      });
    },
    //添加角色
    add() {
      this.dialogFormVisible = true;
    },
    //确定添加
    adds() {
      this.$refs.ruleForm.validate((valid) => {
        if (!valid) return this.$message.error("请填写完整用户信息");
        this.$axios.post("roles", this.form).then((res) => {
          if (res.data.meta.status != 201) {
            this.$message.error("添加用户失败");
          } else {
            this.$message.success("添加用户成功");
            this.dialogFormVisible = false;
            this.getroles();
          }
          this.form = {};
        });
      });
    },
    //编辑
    edit(id) {
      this.id = id;
      this.dialog = true;
      this.$axios.get("roles/" + id).then((res) => {
        if (res.data.meta.status != 200) {
          return this.$message.error("获取用户信息失败");
        }
        this.forms = res.data.data;
      });
    },
    //确定编辑
    editform() {
      this.$refs.editruleForm.validate((valid) => {
        if (!valid) return this.$message.error("请填写完整用户信息");
        this.$axios
          .put("roles/" + this.forms.roleId, this.forms)
          .then((res) => {
            if (res.data.meta.status != 200) {
              this.$message.error("添加用户失败");
            } else {
              this.$message.success("添加用户成功");
              this.dialog = false;
              this.getroles();
            }
          });
      });
    },
    //删除

    del(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$axios.delete("roles/" + id).then((res) => {
            if (res.data.meta.status != 200) {
              this.$message({
                type: "error",
                message: res.data.meta.msg,
              });
            } else {
              this.$message({
                type: "success",
                message: res.data.meta.msg,
              });
              this.getroles();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //权限
    setting(role) {
      this.dialogdata = true;
      this.roleId = role.id;
      this.$axios.get("rights/tree").then((res) => {
        if (res.data.meta.status != 200) {
          return this.$message.error("获取分配权限失败");
        }
        this.rightsdata = res.data.data;
        // 递归获取三级节点
        this.getdefkeys(role, this.defKeys);
      });
    },
    //通过递归 获取角色下的三级权限的所以id 保存到defKeys数组中
    getdefkeys(node, arr) {
      // 如果node不包含children属性,则是三级节点
      if (!node.children) {
        return arr.push(node.id);
      }
      // 递归调用
      node.children.forEach((item) => this.getdefkeys(item, arr));
    },
    setRightDialogClose() {
      this.defKeys = []; // 关闭对话框时 清空选中状态
    },
    //删除角色指定权限
    removeRightById(role, rightId) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$axios
            .delete(`roles/${role.id}/rights/${rightId}`) //返回的是最新的角色权限信息
            .then((res) => {
              console.log(res);
              if (res.data.meta.status != 200) {
                this.$message({
                  type: "error",
                  message: res.data.meta.msg,
                });
              } else {
                this.$message({
                  type: "success",
                  message: res.data.meta.msg,
                });
                role.children = res.data.data; //对现有的角色权限进行更新
              }
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    //确认分配
    settingform() {
      //获取所有选中的以及半选中的内容
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      // 数组转换为拼接的字符串
      const idstr = keys.join(",");
      this.$axios
        .post(`roles/${this.roleId}/rights`, { rids: idstr })
        .then((res) => {
          console.log(res);
          if (res.data.meta.status !== 200)
            return this.$message.error("分配权限失败");

          this.$message.success("分配权限成功");
          this.getroles();
          this.dialogdata = false;
        });
    },
  },
};
</script>

<style scoped lang='scss'>
.box {
  .box1 {
    margin-top: 10px;
    width: 100%;
    background-color: white;
    .el-button {
      margin: 10px 10px;
    }
    .el-table {
      width: 95%;
      margin: 0px 10px 10px 10px;
    }
  }
}
</style>